﻿using System.Text;
using Newtonsoft.Json;
using SE.PO.CInterface.DBProtocols.Devices;
using SE.PO.CInterface.Po.Variables;

namespace SE.PO.CInterface.Web.Clients.Po;

public class VariableClient : CurdClientBase<string, DeviceDto, CreateUpdateDeviceDto>
{
    public override string GetRoute() => "variables";

    public VariableClient(IHttpClientFactory clientFactory, IConfiguration configuration) : base(clientFactory,configuration)
    {
    }

    public new async Task<PageData<VariableDto>?> Get(string? variableName="",string? monitorItem="",List<string>? equipsName=null)
    {
        var sbEquipsName = new StringBuilder();
        if (equipsName!=null&&equipsName.Any())
        {
            foreach (var s in equipsName)
            {
                string text= System.Web.HttpUtility.UrlEncode(s, System.Text.Encoding.UTF8);
                sbEquipsName.Append($"&equipsName={text}");
            }

            
        }
        var client = ClientFactory.CreateClient();
        var request = new HttpRequestMessage
        {
            Method = HttpMethod.Get,
            RequestUri = new Uri($"{BaseUrl}/api/app/variables?name={variableName}&monitorItem={monitorItem}{sbEquipsName}"),
        };
        using var response = await client.SendAsync(request);
        response.EnsureSuccessStatusCode();
        var body = await response.Content.ReadAsStringAsync();
        var items = JsonConvert.DeserializeObject<VariableDto[]>(body);
        if (items != null)
        {
            var pageData = new PageData<VariableDto>
            {
                TotalCount = items.Length,
                Items = items
            };
            Console.WriteLine(body);
            return pageData;
        }

        return default;
    }

}